# Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
# easyAda is licensed under Mulan PubL v2.
# You can use this software according to the terms and conditions of the Mulan PubL v2.
# You may obtain a copy of Mulan PubL v2 at:
#          http://license.coscl.org.cn/MulanPubL-2.0
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PubL v2 for more details.

ifeq ($(component),)
$(error "component: empty")
endif

export BINARY_DIR
export SOURCE_DIR

BINARY_CURRENT_DIR := $(BINARY_DIR)/$(component)
SOURCE_CURRENT_DIR := $(SOURCE_DIR)/$(component)

ifeq ($(CONFIG_DIR),)
    CONFIG_DIR := $(SOURCE_DIR)
endif

-include ${CONFIG_DIR}/.config

obj-y :=
subdir-y  :=

-include ${SOURCE_CURRENT_DIR}/Kbuild

objs := $(addprefix $(BINARY_CURRENT_DIR)/,$(filter %.o,$(obj-y)))

sub_components += $(patsubst %/,%,$(filter %/,$(obj-y)))
sub_components := $(foreach d,$(sub_components),$(component)/$(d))

builtin := $(BINARY_CURRENT_DIR)/built-in.o
sub_builtins := $(foreach sub,$(sub_components),$(BINARY_DIR)/$(sub)/built-in.o)

all : $(builtin)

$(builtin) : $(component)
	$(Q)echo " LD      $@"
	${Q}${LD} --start-group $(objs) $(sub_builtins) --end-group -Map=$@.map ${LDFLAGS} -r -o $@

.PHONY: $(component) $(sub_components)
$(component) : $(BINARY_CURRENT_DIR) $(objs) $(sub_components)

$(BINARY_CURRENT_DIR) : $(BINARY_DIR)
	$(Q)echo ' mkdir   $@'
	$(Q)-mkdir -p $@

$(BINARY_CURRENT_DIR)/%.o : $(SOURCE_CURRENT_DIR)/%.c
	$(Q)echo ' CC      $@'
	${Q}${CC} ${CFLAGS} ${INCLUDES} -M -MF $@.dep -c $< -o $@
	${Q}${CC} ${CFLAGS} ${INCLUDES} -c $< -o $@

$(BINARY_CURRENT_DIR)/%.o : $(SOURCE_CURRENT_DIR)/%.S
	$(Q)echo ' AS      $@'
	${Q}${CC} ${CFLAGS} ${INCLUDES} -M -MF $@.dep -c $< -o $@
	${Q}${CC} ${CFLAGS} ${INCLUDES} -c $< -o $@

self := ${SOURCE_DIR}/scripts/Makefile.build.mk
$(sub_components) :
	$(Q)$(MAKE) -f $(self) component=$@
